package com.kingmed.kmss.framework.mybatis.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kingmed.kmss.common.domain.BaseEntity;
import com.kingmed.kmss.common.dto.admin.ums.LoginUserDTO;
import com.kingmed.kmss.common.dto.admin.ums.OrganizationDTO;
import com.kingmed.kmss.common.enums.base.code.ResultCode;
import com.kingmed.kmss.common.exception.BusinessException;
import com.kingmed.kmss.common.satoken.LoginHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
import java.util.List;

/**
 * MP注入处理器
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                Date current = ObjectUtil.isNotNull(baseEntity.getCreateTime()) ? baseEntity.getCreateTime() : new Date();
                baseEntity.setCreateTime(current);
                //创建时同步set更新时间,注意： 这里需设置为最新时间，因为如果是过去的时间会导致更新时间比审批通过时间小，数据同步会丢失数据
                baseEntity.setUpdateTime(new Date());
                //取用户名,先判断是否被手动set
                //String username = StrUtil.isNotBlank(baseEntity.getCreateBy()) ? baseEntity.getCreateBy() : getLoginUsername();

                //取用户姓名,先判断是否被手动set
                String realName = StrUtil.isNotBlank(baseEntity.getCreateBy()) ? baseEntity.getCreateBy() : getLoginUserRealName();

                Long userId = (baseEntity.getCreateById() != null && baseEntity.getCreateById() != 0)
                        ? baseEntity.getCreateById() : getLoginUserId();

                Long orgId = (baseEntity.getOrgId() != null && baseEntity.getOrgId() != 0)
                        ? baseEntity.getOrgId() : getLoginUserOrgId();

                // 当前已登录 且 创建人为空 则填充
                baseEntity.setCreateBy(realName);
                // 当前已登录 且 创建人为空 则填充
                baseEntity.setCreateById(userId);

                // 当前已登录 且 更新人为空 则填充
                // 创建时同步set更新人
                baseEntity.setUpdateBy(realName);
                // 当前已登录 且 组织ID为空 则填充
                baseEntity.setOrgId(orgId);
            }
        } catch (Exception e) {
            throw new BusinessException("自动注入异常 => " + e.getMessage(), ResultCode.UNAUTHORIZED);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                Date current = new Date();
                // 更新时间填充(不管为不为空)
                baseEntity.setUpdateTime(current);
                String realName = getLoginUserRealName();
                // 当前已登录 更新人填充(不管为不为空)
                if (StrUtil.isNotBlank(realName)) {
                    baseEntity.setUpdateBy(realName);
                }
            }
        } catch (Exception e) {
            throw new BusinessException("自动注入异常 => " + e.getMessage(), ResultCode.UNAUTHORIZED);
        }
    }

    /**
     * 获取登录用户名(sa-token获取)
     */
    private String getLoginUsername() {
        LoginUserDTO loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser.getUsername();
    }

    /**
     * 获取登录用户的Id(sa-token获取)
     */
    private Long getLoginUserId() {
        LoginUserDTO loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser.getId();
    }

    /**
     * 获取登录用户的组织orgId(sa-token获取)
     */
    private Long getLoginUserOrgId() {
        LoginUserDTO loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }

        List<OrganizationDTO> orgs = loginUser.getOrgs();
        Long orgId = 1L;
        if (orgs != null && orgs.size() > 0) {
            orgId = orgs.get(0).getId();
        }

        return orgId;
    }

    //获取登录用户的真实姓名(sa-token获取)
    private String getLoginUserRealName() {
        LoginUserDTO loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser.getNickName();
    }

}
